<template>
  <div id="home">
    <nav-bar class="home-nav">
      <div slot="center">购物街</div>
    </nav-bar>
    <tab-control :titles="['流行', '新款', '精选']" @tabClick="tabClick" ref="tabControl1" class="tab-control" v-show="isTabFixed" />
    <scroll class="content" ref="scroll" :probe-type="3" @scroll="contentScroll" :pull-up-load="true" @pullingUp="loadMore">
      <!-- 完全手写封装轮播，即拿即用 -->
        <home-swiper :hbanners="banners" @swiperImageLoad="swiperImageLoad" />

        <home-recommend-view :hrecommends="recommends"/>
        <home-feature-view />
        <tab-control :titles="['流行', '新款', '精选']" @tabClick="tabClick" ref="tabControl2" />
        <!-- <goods-list :listgoods="goods[currentType].list"/> -->
        <goods-list :listgoods="showGoods"/>
    </scroll>


    <back-top @click.native="backTop" v-show="isShowBackTop"></back-top>
  </div>
</template>
<script>
import HomeSwiper from "./childComps/HomeSwiper";
import HomeRecommendView from "./childComps/HomeRecommendView";
import HomeFeatureView from "./childComps/HomeFeatureView";

import NavBar from "components/common/navbar/NavBar";
import TabControl from "components/content/tabControl/TabControl";
import GoodsList from 'components/content/goods/GoodsList'
import Scroll from 'components/common/scroll/Scroll'

import { getHomeMuitidata, getHomeGoods } from "network/home";

// import {BACKTOP_DISTANCE} from "common/const"
import {itemListenerMixin,backTopMixin} from "common/mixin"
// import BackTop from 'components/content/backTop/BackTop'

export default {
  name: "Home",
  components: {
    HomeSwiper,
    HomeRecommendView,
    HomeFeatureView,
    NavBar,
    TabControl,
    GoodsList,
    Scroll,
    // BackTop,
    
  },
  mixins:[itemListenerMixin,backTopMixin],
  data() {
    return {
      banners: [],
      recommends: [],
      goods: {
        pop: { page: 0, list: [] },
        new: { page: 0, list: [] },
        sell: { page: 0, list: [] },
      },
      currentType:'pop',
      // isShowBackTop:false,
      tabOffsetTop:0,
      isTabFixed:false,
      saveY:0,
    };
  },
  computed:{
    showGoods(){
      return this.goods[this.currentType].list
    }
  },
  /* Home离开时记录状态和位置 开始  BS2.0版本不存在这个问题
  * 有缓存keep-alive时，会调用activated和deactivated
  */
  activated() {//进来Home时
    console.log('activated');
    this.$refs.scroll.scrollTo(0,this.saveY,0);
    this.$refs.scroll.refresh();
  },
  deactivated() {//离开Home时
    // 1.保存Y值
    this.saveY = this.$refs.scroll.getScrollY();
    // 2.取消全局事件监听
    this.$bus.$off('itemImgLoad',this.itemImgListener);
    // this.$bus.$off('itemImgLoad',函数);
  },
  destroyed() {
    console.log('homedestroy');
  },
   /* Home离开时记录状态和位置 end */
  created() {
    // 1.请求多个数据
    this.getHomeMuitidata()
    // 2.请求商品数据
    this.getHomeGoods("pop")
    this.getHomeGoods("new")
    this.getHomeGoods("sell")
  },
  mounted() {
    console.log('首页mounted');
    
    // 监听item中图片加载完成---防抖动
    // 1.图片加载完成的时间见监听
    // let newRefresh = debounce(this.$refs.scroll && this.$refs.scroll.refresh,100)
    // // 对监听的事件进行保存
    // this.itemImgListener = () => {
    //   newRefresh()
    // }
    // this.$bus.$on('itemImageLoad',this.itemImgListener);

  },
  methods: {
    // 事件监听相关的方法
    // debounce(func, delay){// 防抖函数
    //   let timer = null;
    //   return function(...args){
    //     if(timer){clearTimeout(timer)}
    //     timer = setTimeout(() => {
    //       func.apply(this,args)
    //     },delay)
    //   }
    // },
    tabClick(index){
      switch(index){
        case 0:
          this.currentType = 'pop'
          break
        case 1:
          this.currentType = 'new'
          break
        case 2:
          this .currentType = 'sell'
          break
      }
      this.$refs.tabControl1.currentIndex = index;
      this.$refs.tabControl2.currentIndex = index;
    },
    // 用混入mixin.js
    // backTop(){
    //   // 返回顶部
    //   this.$refs.scroll.scrollTo(0,0,300);
    // },
    contentScroll(position){//回到顶部显示/隐藏
      // 1.判断BackTop是否显示
      // this.isShowBackTop = (-position.y) > 1000
      this.listenShowBackTop(position);//用混入

      // 2.决定tabControl是否吸顶（position：fixed）
      this.isTabFixed = (-position.y) > this.tabOffsetTop
      
    },
    loadMore(){
      this.getHomeGoods(this.currentType)
    },
    swiperImageLoad(){
      // 所有的组件都有一个属性$el：用于获取组件中的DOM元素
      console.log('offsetTop--',this.$refs.tabControl2.$el.offsetTop);
      this.tabOffsetTop = this.$refs.tabControl2.$el.offsetTop
    },
  
    // 网络请求相关的方法
    getHomeMuitidata() {
      getHomeMuitidata().then((res) => {
        this.banners = res.data.banner.list;
        this.recommends = res.data.recommend.list;
      });
    },
    getHomeGoods(type) {
      const page = this.goods[type].page + 1;
      getHomeGoods(type, page).then((res) => {
        this.goods[type].list.push(...res.data.list);
        this.goods[type].page += 1;

        // 监测到上拉刷新的动作之后，pullingUp 事件的消费机会只有一次，因此你需要调用 finishPullUp() 来告诉 BetterScroll 来提供下一次 pullingUp 事件的消费机会。
        // 完成上拉加载更多
        this.$refs.scroll.finishPullUp();
      });
    },
    
  }
};
</script>
<style scoped>
#home {
  /* padding-top: 44px; */
  height: 100vh;
  position: relative;
}
.home-nav {
  color: #fff;
  background-color: var(--color-tint);
/* 在使用浏览器原生滚动时，为了让导航不跟随一起滚动
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: 9; */
}

.content{
  overflow: hidden;
  position: absolute;
  top: 44px;
  bottom: 49px;
  left: 0;
  right: 0;
}
/* 或： */
/* .content{
  height: calc(100% - 103px);
  overflow: hidden;
  margin-top:44px;
} */

.tab-control{
  position: relative;
  z-index: 9;
}
</style>
